package com.wcity.manage.web.community;

import com.wcity.manage.common.utils.OSSUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 图片上传服务（社区）
 * Created by hgg on 2016/12/27.
 */
@Controller
public class ImageAct {

    private static final String PICSUFFIXS = ".jpg.jpeg.png.gif.JPG.JPEG.PNG.GIF";
    private final static Logger log = LoggerFactory.getLogger( ImageAct.class );

    /**
     * 图片服务
     * @param multipartFile
     * @param request
     */
    @RequestMapping(value = "community_image_service")
    @ResponseBody
    public String imageUpload(@RequestParam("fileName")MultipartFile multipartFile, HttpServletRequest request  ){

        String originalFilename = multipartFile.getOriginalFilename();
        String picSuffix = originalFilename.substring( originalFilename.indexOf(".") );
        if( PICSUFFIXS.indexOf( picSuffix ) == -1 ){
            return null;
        }

        String fileName = new Date().getTime() + picSuffix;
        try{

            //上传文件到阿里云
            InputStream input = multipartFile.getInputStream();
            String key = OSSUtil.FILEPATH + fileName;
            OSSUtil.uploadFile( input, key, multipartFile.getSize() );

            return OSSUtil.OSS_URLPREFIX + "/" + key;
        }catch ( Exception e ){
            log.error( "上传文件到阿里云发生异常." + e.getMessage() );
          return null;
        }
    }
}
